const explain = require("explain")
const uniID = require('uni-id')

module.exports = class course extends explain.service {
	async index(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate

		return await db.collection('courses').aggregate()
			.lookup({
				from: 'videos',
				let: {
					id: '$_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$course_id', '$$id'])))
					.group({
						_id: null,
						totalDuration: $.sum('$duration'),
						count: $.sum(1),
					})
					.project({
						_id: 0,
						totalDuration: 1,
						count: 1
					})
					.done(),
				as: 'videos'
			})
			.lookup({
				from: 'study-records',
				let: {
					id: '$_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.and([
						$.eq(['$course_id', '$$id']),
						$.eq(['$user_id', payload.uid])
					])))
					.group({
						_id: null,
						studyDuration: $.sum('$current_time')
					})
					.project({
						_id: 0,
						studyDuration: 1
					})
					.done(),
				as: 'records'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([$.arrayElemAt(['$videos', 0]), $.arrayElemAt(['$records', 0]),
					'$$ROOT'
				])
			})
			.project({
				videos: 0,
				records: 0
			})
			.end()
	}
}
